import prisma from '../../utils/prisma'
import { verifyPassword, signToken } from '../../utils/auth'

export default defineEventHandler(async (event: any) => {
  try {
    const body = await readBody(event)
    const { username, password } = body
    
    // 参数验证
    if (!username || !password) {
      throw createError({
        statusCode: 400,
        statusMessage: '用户名和密码不能为空'
      })
    }
    
    // 查询用户
    const user = await prisma.user.findUnique({
      where: { username }
    })
    
    if (!user) {
      throw createError({
        statusCode: 401,
        statusMessage: '用户不存在'
      })
    }
    
    // 验证密码
    const isValidPassword = await verifyPassword(password, user.password)
    console.log("我的验证密码",isValidPassword);
    
    if (!isValidPassword) {
      throw createError({
        statusCode: 401,
        statusMessage: '用户名或密码错误'
      })
    }
    
    // 生成JWT令牌
    const token = signToken(user.id, user.username)
    
// 在登录成功的部分添加：
const updatedUser = await prisma.user.update({
  where: { id: user.id },
  data: { lastLoginAt: new Date() }
})

// 返回包含时间戳的用户信息
const { ...userWithoutPassword } = updatedUser
return {
  code: 200,
  message: '登录成功',
  data: {
    token,
    user: userWithoutPassword
  }
}
    
  } catch (error: any) {
    throw createError({
      statusCode: error.statusCode || 500,
      statusMessage: error.message || '内部服务器错误'
    })
  }
})